package cn.wolfcode.luowowo.website.web.intersepter;


import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.web.util.CookieUtil;
import cn.wolfcode.luowowo.website.web.annotation.RequireLogin;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
public class CheckLoginIntersepter implements HandlerInterceptor {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        String token = CookieUtil.getToken(request,response);
        UserInfo userInfo = userInfoRedisService.getUserInfoByToken(token);
        //只拦截动态请求方法
        if (handler instanceof HandlerMethod){
            HandlerMethod hm = (HandlerMethod) handler;
            //判断该方法是否贴了自定义注解
            if (hm.hasMethodAnnotation(RequireLogin.class)){
                //贴了,判断是否登录

                //没有登录,跳转页面
                if (userInfo==null){
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        request.getSession().setAttribute("userInfo",userInfo);
        return true;
    }
}
